import maze_generator
import dp_solver
import dp2_solver
import puzzle_solver
import clue_generator
import Lock
import json
import pygame
import sys
import time
from gui_interface import run_gui_setup

# 颜色定义
COLORS = {
    'wall': (50, 50, 50),      # 深灰色 - 墙壁
    'empty': (255, 255, 255),  # 白色 - 空地
    'start': (0, 255, 0),      # 绿色 - 起点
    'end': (255, 0, 0),        # 红色 - 终点
    'coin': (255, 215, 0),     # 金色 - 金币
    'trap': (255, 100, 100),   # 浅红色 - 陷阱
    'lock': (128, 0, 128),     # 紫色 - 锁
    'boss': (255, 165, 0),     # 橙色 - Boss
    'path': (135, 206, 235),   # 天蓝色 - 路径
    'current': (255, 255, 0),  # 黄色 - 当前位置
    'visited': (173, 216, 230) # 淡蓝色 - 已访问
}

def get_cell_color(cell_type):
    """根据格子类型返回对应颜色"""
    mapping = {
        '#': COLORS['wall'],
        ' ': COLORS['empty'],
        'S': COLORS['start'],
        'E': COLORS['end'],
        'G': COLORS['coin'],
        'T': COLORS['trap'],
        'L': COLORS['lock'],
        'B': COLORS['boss']
    }
    return mapping.get(cell_type, COLORS['empty'])

def visualize_maze_with_path(maze, path, max_value):
    """Visualize maze with path animation using pygame"""
    pygame.init()
    
    # Maze dimensions
    rows = len(maze)
    cols = len(maze[0])
    cell_size = 40
    
    # Window dimensions
    window_width = cols * cell_size
    window_height = rows * cell_size + 100  # Extra space for info display
    
    # Create window
    screen = pygame.display.set_mode((window_width, window_height))
    pygame.display.set_caption("Maze Path Visualization")
    
    # Font
    font = pygame.font.Font(None, 24)
    
    # Animation state
    current_step = 0
    last_update_time = pygame.time.get_ticks()
    step_delay = 333  # 333ms per step (3 steps per second)
    
    clock = pygame.time.Clock()
    running = True
    animation_complete = False
    
    print("Starting automatic path animation...")
    print("Press ESC to exit or close window")
    
    while running:
        current_time = pygame.time.get_ticks()
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                elif event.key == pygame.K_r:
                    # R key: Reset
                    current_step = 0
                    animation_complete = False
                    last_update_time = current_time
        
        # Auto advance animation
        if not animation_complete and current_time - last_update_time >= step_delay:
            if current_step < len(path):
                current_step += 1
                last_update_time = current_time
            else:
                animation_complete = True
                print(f"Animation completed!")
        
        # Clear screen
        screen.fill((220, 220, 220))
        
        # Draw maze
        for i in range(rows):
            for j in range(cols):
                x = j * cell_size
                y = i * cell_size
                
                # Get base color
                color = get_cell_color(maze[i][j])
                
                # Check if on path
                if current_step > 0 and (i, j) in path[:current_step]:
                    if (i, j) == path[current_step-1]:
                        # Current position
                        color = COLORS['current']
                    else:
                        # Visited position
                        color = COLORS['visited']
                
                # Draw cell
                pygame.draw.rect(screen, color, (x, y, cell_size, cell_size))
                pygame.draw.rect(screen, (0, 0, 0), (x, y, cell_size, cell_size), 2)
                
                # Draw symbols
                if maze[i][j] != ' ' and maze[i][j] != '#':
                    text = font.render(maze[i][j], True, (0, 0, 0))
                    text_rect = text.get_rect(center=(x + cell_size//2, y + cell_size//2))
                    screen.blit(text, text_rect)
        
        # Display information
        info_y = rows * cell_size + 10
        
        # Step information
        step_text = f"Step: {current_step}/{len(path)}"
        step_surface = font.render(step_text, True, (0, 0, 0))
        screen.blit(step_surface, (10, info_y))
        
        # Current position information
        if current_step > 0 and current_step <= len(path):
            pos = path[current_step-1]
            pos_text = f"Position: ({pos[0]}, {pos[1]})"
            pos_surface = font.render(pos_text, True, (0, 0, 0))
            screen.blit(pos_surface, (200, info_y))
        
        # Status and controls
        status_text = f"Complete! Max value: {max_value}" if animation_complete else "Auto Playing..."
        status_surface = font.render(status_text, True, (0, 150, 0) if animation_complete else (0, 0, 150))
        screen.blit(status_surface, (10, info_y + 30))
        
        control_text = "Controls: R-Reset, ESC-Exit"
        control_surface = font.render(control_text, True, (0, 0, 0))
        screen.blit(control_surface, (10, info_y + 55))
        
        pygame.display.flip()
        clock.tick(60)
    
    pygame.quit()

if __name__ == "__main__":
    # 使用GUI界面获取用户设置
    print("启动游戏设置界面...")
    settings = run_gui_setup()
    
    if not settings:
        print("游戏已取消")
        sys.exit(0)
    
    print(f"设置完成！")
    
    if settings['load_mode']:
        # 从文件加载模式
        print(f"从文件加载迷宫")
        print(f"迷宫尺寸: {settings['maze_size']}x{settings['maze_size']}")
        print(f"线索数量: {len(settings['selected_clues'])}")
        
        # 使用加载的数据
        input_dict = settings['loaded_data']
        maze = input_dict["maze"]
        
        print("迷宫数据已从文件加载！")
    else:
        # 生成新迷宫模式
        print(f"迷宫尺寸: {settings['maze_size']}x{settings['maze_size']}")
        print(f"密码: {settings['password']}")
        print(f"选择的线索: {settings['selected_clues']}")
        
        # 生成迷宫
        print(f"\n正在生成 {settings['maze_size']}x{settings['maze_size']} 迷宫...")
        generator = maze_generator.MazeGenerator(settings['maze_size'])
        maze = generator.generate_maze()
        
        # 保存迷宫到文件
        generator.save_to_json()
        generator.save_to_csv()
        print("迷宫生成完成！")
        
        # 准备输入数据
        input_dict = {
            "maze": maze,
            "L": settings['password_hash'],
            "C": settings['selected_clues']
        }
        
        # 保存到input.json
        with open("./input.json", "w", encoding="utf-8") as f:
            json.dump(input_dict, f, indent=2, ensure_ascii=False)
        print("已将输入数据保存到 input.json")
    
    # 使用动态规划求解最优路径
    print("\n正在计算最优路径...")
    print("\n==========dp1==========\n")
    max_value, path = dp_solver.solve_maze_combined_state(input_dict["maze"], coin_value=5, trap_penalty=-3)
    print(f"dp1最大收益: {max_value}")
    print(f"dp1路径长度: {len(path)}")
    print("dp1路径:", path)
    print("\n==========dp2==========\n")
    max_value2, path2 = dp2_solver.solve_maze_all_items(input_dict["maze"], coin_value=5, trap_penalty=-3, boss_penalty=-1, locker_penalty=-7)
    print(f"dp2最大收益: {max_value2}")
    print(f"dp2路径长度: {len(path2)}")
    print("dp2路径:", path2)
    
    # 检查是否需要求解密码
    has_password = 'L' in input_dict and input_dict['L']
    has_clues = 'C' in input_dict and input_dict['C']
    
    if has_password and has_clues:
        # 求解密码
        print("\n正在求解密码...")
        steps, password = puzzle_solver.solve_password(input_dict["C"], input_dict["L"], 1000)
        print(f"密码在{steps}步内找到，密码为: {password}")
    else:
        print("\n跳过密码求解 - JSON文件中缺少密码相关字段 (L 或 C)")
    
    # Launch maze visualization
    print("\nLaunching maze visualization...")
    print("The path will be automatically animated at 3 steps per second")
    
    visualize_maze_with_path(input_dict["maze"], path, max_value)
    
    print("\n游戏结束！")
    